/**
 * 获取带参数的二维码
 * 参考 http://mp.weixin.qq.com/wiki/18/28fc21e7ed87bec960651f0ce873ef8a.html
 */
var util = require('../util'),
    https = require('https'),
    Promise = require('bluebird'),
    weixinuser = require('../db').weixinuser;

function getQrticket(accessToken, scene_id) {
  return new Promise(function (resolve, reject) {

    var api = '/cgi-bin/qrcode/create?access_token=' + accessToken,
        postData = JSON.stringify({
          "expire_seconds": 604800,
          "action_name": "QR_SCENE",
          "action_info": {
            "scene": {
              "scene_id": + scene_id
            }
          }
        });
    var options = {
      hostname: 'api.weixin.qq.com',
      port    : 443,
      path    : api,
      method  : 'POST',
      headers : {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    };

    var req = https.request(options, function (res) {
      var result = '';
      res.on('data', function (chunk) {
        result += chunk;
      });
      res.on('end', function () {
        resolve(result);
      });
    });
    req.on('error', function (err) {
      reject(err);
    });
    req.write(postData);
    req.end();
  });
}

/**
 * 通过openid取得用户的推广二维码(带参数的二维码)
 * @returns {string} 二维码url
 */
function getQrcode(userInfo) {

  return new Promise(function (resolve, reject) {

    if (userInfo.qrcode) {
      resolve(userInfo.qrcode);
    } else {
      // access token
      util.weixin.getAccessToken(userInfo.openid).then(function (data) {
        var accessToken = data.access_token,
            userPromotionCode = userInfo.promotion_code;

        // 获得二维码的ticket
        getQrticket(accessToken, userPromotionCode).then(function (strTicketJson) {

          // 返回二维码url
          resolve('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + JSON.parse(strTicketJson).ticket);
        });
      }).catch(util.log.log2Error);
    }
  });
};

module.exports.getQrcode = getQrcode;
